package org.william.shiro.config;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.william.shiro.realm.UserRealm;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {

    //ShiroFilterFactoryBean
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager securityManager){
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();

        /**
         * shiro内置过滤器
         * anon:无需认证可以访问
         * authc:需要认证才能访问
         * user:拥有记住我才能访问
         * perms:拥有某个资源的权限才能访问
         * role:拥有某个角色才能访问
         */
        Map<String, String> filterMap = new LinkedHashMap<>();
        filterMap.put("/user/add", "perms[user:add]");
        filterMap.put("/user/edit", "perms[user:edit]");
        filterMap.put("/user/**","authc");
        bean.setFilterChainDefinitionMap(filterMap);

        //设置安全管理器
        bean.setSecurityManager(securityManager);

        //设置登录页
        bean.setLoginUrl("/login");

        bean.setUnauthorizedUrl("/unauth");
        return bean;
    }

    //DefaultWebSecurityManager
    @Bean(name = "securityManager")
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //关联userRealm
        securityManager.setRealm(userRealm);
        return securityManager;
    }

    //自定义realm
    @Bean
    public UserRealm userRealm(){
        return new UserRealm();
    }

    //整合shiroDialect:
    @Bean
    public ShiroDialect getShiroDialect(){
        return new ShiroDialect();
    }
}
